import React from 'react'
import Loader from 'halogen/PulseLoader'
import Element from './Element'
import ReactAddonsUpdate from 'react-addons-update'
import EventEmitter from '../libs/eventEmitter'
import $ from 'jquery'
import autobind from 'autobind-decorator'

@autobind
export default class RegionalDesign extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      data: null, loading: true, error: null, object_name: '', object_type: '', children_object_type: ''
    };
    this.init_state = this.state;
  }

  getConfig(props, key) {
    const config = {
      repo: {
        object_url: '/regional_design/repos',
        children_object_url: '/regional_design/drug_repos',
        children_param_name: 'drug_repo'
      },
      drug_repo: {
        object_url: '/regional_design/drug_repos',
        children_object_url: '/regional_design/drug_brandrethes',
        children_param_name: 'drug_brandreth'
      },
      drug_brandreth: {
        object_url: '/regional_design/drug_brandrethes',
        children_object_url: '/regional_design/drug_brandreth_grids',
        children_param_name: 'drug_brandreth_grid'
      }
    }
    const search_str = props.location.search
    return config[search_str.substring(search_str.indexOf("=") + 1)][key]
  }

  componentDidMount() {
    const url = this.getConfig(this.props, 'object_url') + '/' + this.props.match.params.id + '.json'
    this.getJSON(url)

    EventEmitter.subscribe('moveDropZone', function(element){
      if (element.target_type === this.state.object_type) {
        this.addElement(element)
      } else {
        EventEmitter.dispatch('alert', '不能移动该元件')
      }
    }.bind(this))

    EventEmitter.subscribe('element:update', function(element){
      this.updateElement(element)
    }.bind(this))
  }

  addElement(element) {
    const new_element = {
      name: element.name,
      pos_x: element.initialPos.x,
      pos_y: element.initialPos.y,
      parent_id: this.props.match.params.id
    }

    const url = this.getConfig(this.props, 'children_object_url') + '.json'
    let data = {}
    data[this.getConfig(this.props, 'children_param_name')] = new_element

    $.post(url, data, function(data) {
      EventEmitter.dispatch('alert', '添加元件成功')
      element.id = data.id
      element.children_object_type = this.state.children_object_type
      const elements = ReactAddonsUpdate(this.state.data, { $push: [element] })
      this.setState({data: elements})
    }.bind(this), 'JSON')
  }

  updateElement(element) {
    let data = {}
    data[this.getConfig(this.props, 'children_param_name')] = element

    $.ajax({
      method: 'PUT',
      url: this.getConfig(this.props, 'children_object_url') + '/' + element.id,
      dataType: 'JSON',
      data: data,
      success: function(data) {
      }
    })
  }

  componentWillUnmount() {
    EventEmitter.unSubscribe('moveDropZone')
    EventEmitter.unSubscribe('element:update')
  }

  componentWillReceiveProps(nextProps) {
    this.setState(this.init_state)
    const url = this.getConfig(nextProps, 'object_url') + '/' + nextProps.match.params.id + '.json'
    this.getJSON(url)
  }

  getJSON(url) {
    $.getJSON(url).then(
      value => this.setState({loading: false, data: value.children, object_name: value.name, object_type: value.type, children_object_type: value.children_object_type}),
      error => this.setState({loading: false, error: error}))
  }

  render() {
    if (this.state.loading) {
      return (
        <Loader color="#286090" size="12px" margin="4px"/>
      )
    }
    else if (this.state.error !== null) {
      return <span>Error: {this.state.error}</span>
    }
    else {
      const data = this.state.data.map(function(element) {
        return (
          <Element hashHistory={ this.props.history } childrenObjectType={ this.state.children_object_type } isDropZoneChild={ true } key={ element.id } id={ element.id } name={ element.name } initialPos={ element.initialPos } />
        )
      }.bind(this))

      return (
        <div>
          <h1 className='text-center'>{ this.state.object_name }</h1>
          <div>{ data }</div>
        </div>
      )
    }
  }
}
